<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-row :gutter="20">
        <el-col :span="18">
          <h2>排课统计分析</h2>
          <p class="page-description">智能排课结果的统计分析和可视化展示，帮助评估排课质量和优化效果</p>
        </el-col>
        <el-col :span="6" class="text-right">
          <el-button type="primary" icon="el-icon-refresh" @click="refreshData">刷新数据</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 统计概览 -->
    <el-row :gutter="20" class="stats-overview">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon total-courses">
              <i class="el-icon-document"></i>
            </div>
            <div class="stats-info">
              <h3>{{ overviewData.totalCourses }}</h3>
              <p>总课程数</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon scheduled-courses">
              <i class="el-icon-check"></i>
            </div>
            <div class="stats-info">
              <h3>{{ overviewData.scheduledCourses }}</h3>
              <p>已排课程</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon avg-score">
              <i class="el-icon-star-on"></i>
            </div>
            <div class="stats-info">
              <h3>{{ overviewData.avgScore }}分</h3>
              <p>平均评分</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon success-rate">
              <i class="el-icon-success"></i>
            </div>
            <div class="stats-info">
              <h3>{{ overviewData.successRate }}%</h3>
              <p>排课成功率</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="学期" prop="semester">
          <el-select v-model="queryParams.semester" placeholder="请选择学期" clearable>
            <el-option
              v-for="semester in semesterOptions"
              :key="semester.value"
              :label="semester.label"
              :value="semester.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务ID" prop="taskId">
          <el-input
            v-model="queryParams.taskId"
            placeholder="请输入任务ID"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="统计时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['jwgl:schedule:statistics:export']"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-pie-chart"
            size="mini"
            @click="showChartDialog = true"
          >图表分析</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-card>

    <!-- 统计列表 -->
    <el-card>
      <el-table v-loading="loading" :data="statisticsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="统计ID" align="center" prop="id" width="80" />
        <el-table-column label="任务ID" align="center" prop="taskId" width="80" />
        <el-table-column label="学期" align="center" prop="semester" width="120" />
        <el-table-column label="总课程数" align="center" prop="totalCourses" width="100" />
        <el-table-column label="已排课程" align="center" prop="scheduledCourses" width="100" />
        <el-table-column label="冲突数量" align="center" prop="conflictCount" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.conflictCount > 0 ? 'danger' : 'success'">
              {{ scope.row.conflictCount }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="教师满意度" align="center" prop="teacherSatisfaction" width="120">
          <template slot-scope="scope">
            <el-progress
              :percentage="scope.row.teacherSatisfaction"
              :stroke-width="8"
              :show-text="true"
              :color="getProgressColor(scope.row.teacherSatisfaction)"
            ></el-progress>
          </template>
        </el-table-column>
        <el-table-column label="教室利用率" align="center" prop="roomUtilization" width="120">
          <template slot-scope="scope">
            <el-progress
              :percentage="scope.row.roomUtilization"
              :stroke-width="8"
              :show-text="true"
              :color="getProgressColor(scope.row.roomUtilization)"
            ></el-progress>
          </template>
        </el-table-column>
        <el-table-column label="总体评分" align="center" prop="overallScore" width="100">
          <template slot-scope="scope">
            <el-rate
              :value="getRateValue(scope.row.overallScore)"
              disabled
              show-score
              text-color="#ff9900"
            />
          </template>
        </el-table-column>
        <el-table-column label="迭代次数" align="center" prop="iterationCount" width="100" />
        <el-table-column label="执行时间" align="center" prop="executionTime" width="120">
          <template slot-scope="scope">
            <span>{{ formatExecutionTime(scope.row.executionTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleDetail(scope.row)"
              v-hasPermi="['jwgl:schedule:statistics:query']"
            >详情</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-pie-chart"
              @click="handleChart(scope.row)"
            >图表</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['jwgl:schedule:statistics:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 统计详情对话框 -->
    <el-dialog title="统计详情" :visible.sync="detailVisible" width="800px" append-to-body>
      <statistics-detail
        v-if="detailVisible"
        :statistics-id="selectedStatisticsId"
        @close="detailVisible = false"
      />
    </el-dialog>

    <!-- 图表分析对话框 -->
    <el-dialog title="图表分析" :visible.sync="showChartDialog" width="1200px" append-to-body>
      <statistics-charts
        v-if="showChartDialog"
        :query-params="queryParams"
        @close="showChartDialog = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  listScheduleStatistics,
  getScheduleStatistics,
  delScheduleStatistics,
  getSemesterSummary,
  exportScheduleStatistics
} from '@/api/jwgl/scheduleStatistics'
import StatisticsDetail from './components/StatisticsDetail'
import StatisticsCharts from './components/StatisticsCharts'

export default {
  name: 'ScheduleStatistics',
  components: {
    StatisticsDetail,
    StatisticsCharts
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 统计数据列表
      statisticsList: [],
      // 详情对话框
      detailVisible: false,
      // 图表对话框
      showChartDialog: false,
      // 选中的统计ID
      selectedStatisticsId: null,
      // 日期范围
      dateRange: [],
      // 概览数据
      overviewData: {
        totalCourses: 0,
        scheduledCourses: 0,
        avgScore: 0,
        successRate: 0
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        semester: null,
        taskId: null
      },
      // 学期选项
      semesterOptions: [
        { label: '2024-2025学年第一学期', value: '2024-2025-1' },
        { label: '2024-2025学年第二学期', value: '2024-2025-2' },
        { label: '2025-2026学年第一学期', value: '2025-2026-1' },
        { label: '2025-2026学年第二学期', value: '2025-2026-2' }
      ]
    }
  },
  created() {
    this.getList()
    this.getOverviewData()
  },
  methods: {
    /** 查询统计列表 */
    getList() {
      this.loading = true
      // 处理日期范围
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.beginTime = this.dateRange[0]
        this.queryParams.endTime = this.dateRange[1]
      } else {
        this.queryParams.beginTime = null
        this.queryParams.endTime = null
      }
      
      listScheduleStatistics(this.queryParams).then(response => {
        this.statisticsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    
    /** 获取概览数据 */
    getOverviewData() {
      // 计算概览统计
      listScheduleStatistics({ pageNum: 1, pageSize: 1000 }).then(response => {
        const data = response.rows || []
        if (data.length > 0) {
          this.overviewData.totalCourses = data.reduce((sum, item) => sum + (item.totalCourses || 0), 0)
          this.overviewData.scheduledCourses = data.reduce((sum, item) => sum + (item.scheduledCourses || 0), 0)
          this.overviewData.avgScore = data.length > 0 ? 
            Math.round(data.reduce((sum, item) => sum + (item.overallScore || 0), 0) / data.length) : 0
          this.overviewData.successRate = this.overviewData.totalCourses > 0 ? 
            Math.round((this.overviewData.scheduledCourses / this.overviewData.totalCourses) * 100) : 0
        }
      })
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    
    /** 查看详情 */
    handleDetail(row) {
      this.selectedStatisticsId = row.id
      this.detailVisible = true
    },
    
    /** 查看图表 */
    handleChart(row) {
      this.queryParams.taskId = row.taskId
      this.showChartDialog = true
    },
    
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除统计记录编号为"' + ids + '"的数据项？').then(function() {
        return delScheduleStatistics(ids)
      }).then(() => {
        this.getList()
        this.getOverviewData()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    
    /** 导出按钮操作 */
    handleExport() {
      this.download('jwgl/schedule/statistics/export', {
        ...this.queryParams
      }, `statistics_${new Date().getTime()}.xlsx`)
    },
    
    /** 刷新数据 */
    refreshData() {
      this.getList()
      this.getOverviewData()
      this.$modal.msgSuccess('数据刷新成功')
    },
    
    /** 获取进度条颜色 */
    getProgressColor(percentage) {
      if (percentage >= 80) return '#67C23A'
      if (percentage >= 60) return '#E6A23C'
      return '#F56C6C'
    },
    
    /** 获取评分星级 */
    getRateValue(score) {
      return Math.round(score / 20) // 100分制转5星制
    },
    
    /** 格式化执行时间 */
    formatExecutionTime(milliseconds) {
      if (!milliseconds) return '0秒'
      
      const seconds = Math.floor(milliseconds / 1000)
      const minutes = Math.floor(seconds / 60)
      const hours = Math.floor(minutes / 60)
      
      if (hours > 0) {
        return `${hours}小时${minutes % 60}分钟`
      } else if (minutes > 0) {
        return `${minutes}分钟${seconds % 60}秒`
      } else {
        return `${seconds}秒`
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.page-header {
  margin-bottom: 20px;
  
  h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 500;
  }
  
  .page-description {
    margin: 8px 0 0 0;
    color: #909399;
    font-size: 14px;
  }
}

.stats-overview {
  margin-bottom: 20px;
  
  .stats-card {
    .stats-content {
      display: flex;
      align-items: center;
      
      .stats-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        
        i {
          font-size: 24px;
          color: #fff;
        }
        
        &.total-courses {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        &.scheduled-courses {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
        
        &.avg-score {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
        
        &.success-rate {
          background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }
      }
      
      .stats-info {
        h3 {
          margin: 0;
          font-size: 28px;
          font-weight: 600;
          color: #303133;
        }
        
        p {
          margin: 4px 0 0 0;
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }
}

.search-card {
  margin-bottom: 20px;
}

.text-right {
  text-align: right;
}
</style>